package org.jeecg.modules.inspection.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonDefine;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.inspection.entity.Inspection;
import org.jeecg.modules.inspection.entity.InspectionTaskRank;
import org.jeecg.modules.inspection.entity.InspectionTaskRankData;
import org.jeecg.modules.inspection.service.IInspectionLineService;
import org.jeecg.modules.inspection.service.IInspectionService;
import org.jeecg.modules.inspection.vo.InspectionReportVO;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;


/**
 * @Description: 巡检主表
 * @Author: jeecg-boot
 * @Date:   2019-09-26
 * @Version: V1.0
 */
@Slf4j
@Api(tags="巡检主表")
@RestController
@RequestMapping("/b/ins/process")
public class InspectionController {
	@Autowired
	private IInspectionService inspectionService;

	@Autowired
	private IInspectionLineService inspectionLineService;

	 @Autowired
	 private ISysUserRoleService sysUserRoleService;

	/**
	  * 分页列表查询
	 * @param inspection
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "巡检主表-分页列表查询")
	@ApiOperation(value="巡检主表-分页列表查询", notes="巡检主表-分页列查表询")
	@GetMapping(value = "/list")
	public Result<IPage<Inspection>> queryPageList(Inspection inspection,
												   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												   HttpServletRequest req) {
		List<String> officeIds = sysUserRoleService.queryOfficeIds(inspection);
		if(officeIds != null && officeIds.size() > 0){
			inspection.setSqlMap(" and d.office_id in ('"+String.join("','",officeIds)+"') ");
		}else{
			inspection.setSqlMap(" and d.office_id = '' ");
		}

		Result<IPage<Inspection>> result = new Result<>();
		Page<Inspection> pageList = new Page<>(pageNo, pageSize);
		pageList = inspectionService.listByProject(pageList,inspection);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	 @AutoLog(value = "巡检主表-查询巡检报告")
	 @ApiOperation(value="巡检主表-查询巡检报告", notes="巡检主表-查询巡检报告")
	 @GetMapping(value = "/queryReportByLine")
	 public Result<JSONArray> queryReportByLine(@RequestParam(name="processId") String processId) {
		 List<InspectionReportVO> reportVOS = inspectionService.queryReportByLine(processId);
		 return Result.ok(generateReport(reportVOS));
	 }

	private JSONArray generateReport(List<InspectionReportVO> reportVOS){
		JSONArray result = new JSONArray();
		if(reportVOS == null || reportVOS.size() == 0){
			return result;
		}
		Map<String, List<InspectionReportVO>> maps = reportVOS.stream().collect(Collectors.groupingBy(InspectionReportVO :: getAreaId));
		for (Map.Entry<String,List<InspectionReportVO>> entry : maps.entrySet()){
			List<InspectionReportVO> list = entry.getValue();
			JSONObject json = new JSONObject();

			InspectionReportVO line = list.get(0);
			json.put("name",line.getAreaName());
			//状态为300，并且检查结果是正常的
			if(CommonConstant.INSPECTION_STATUS_300.equals(line.getAreaStatusId()) && line.getAreaIsCheckRes() == 0){
				json.put("desc","所辖 "+line.getAreaName()+" 各项检查结果均好，无任何异常情况");
				json.put("items",null);
				json.put("status",0);
				result.add(json);
			}else{
				if(CommonConstant.INSPECTION_STATUS_300.equals(line.getAreaStatusId())){
					json.put("desc","所辖 "+line.getAreaName()+" 除以上所列异常外，其余均正常");
					json.put("status",1);
				}else{
					json.put("desc","所辖 "+line.getAreaName()+" 超时未完成巡检");
					json.put("status",2);
				}
				Map<String, List<InspectionReportVO>> itemMaps = list.stream().collect(Collectors.groupingBy(InspectionReportVO :: getItemId));
				JSONArray itemArray = new JSONArray();
				for (Map.Entry<String,List<InspectionReportVO>> itemEntry : itemMaps.entrySet()){
					List<InspectionReportVO> execList = itemEntry.getValue();
					InspectionReportVO item = execList.get(0);
					if(StringUtils.isBlank(item.getItemName())){
						continue;
					}
					JSONObject itemObj = new JSONObject();
					itemObj.put("name",item.getItemName());
					String isCheck = "未巡检";
					if(item.getItemIsCheck() != null && item.getItemIsCheck() == 1){
						isCheck = "已巡检";
					}
					itemObj.put("status",isCheck);
					JSONArray execArray = new JSONArray();
					for (InspectionReportVO execVo : execList){
						if(StringUtils.isBlank(execVo.getExecExplain())){
							continue;
						}
						JSONObject execObj = new JSONObject();
						execObj.put("context",execVo.getExecExplain());
						String comfirmRes = "未解决";
						if(execVo.getExecComfirmRes() != null && execVo.getExecComfirmRes() == 1){
							comfirmRes = "已解决";
						}
						execObj.put("status",comfirmRes);
						execArray.add(execObj);
					}
					itemObj.put("exceptions",execArray);
					itemArray.add(itemObj);
				}
				json.put("items",itemArray);
				result.add(json);
			}
		}
		log.info("结果="+result);
		return result;
	}

	public static void main(String[] args) {
		Integer i = 1;

		System.out.println(i.equals(1));
	}
	/**
	  *   添加
	 * @param inspection
	 * @return
	 */
	@AutoLog(value = "巡检主表-添加")
	@ApiOperation(value="巡检主表-添加", notes="巡检主表-添加")
	@PostMapping(value = "/add")
	public Result<Inspection> add(@RequestBody Inspection inspection) {
		Result<Inspection> result = new Result<Inspection>();
		try {
			inspectionService.save(inspection);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param inspection
	 * @return
	 */
	@AutoLog(value = "巡检主表-编辑")
	@ApiOperation(value="巡检主表-编辑", notes="巡检主表-编辑")
	@PutMapping(value = "/edit")
	public Result<Inspection> edit(@RequestBody Inspection inspection) {
		Result<Inspection> result = new Result<Inspection>();
		Inspection inspectionEntity = inspectionService.getById(inspection.getId());
		if(inspectionEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = inspectionService.updateById(inspection);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "巡检主表-通过id删除")
	@ApiOperation(value="巡检主表-通过id删除", notes="巡检主表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			inspectionService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "巡检主表-批量删除")
	@ApiOperation(value="巡检主表-批量删除", notes="巡检主表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<Inspection> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<Inspection> result = new Result<Inspection>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.inspectionService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "巡检主表-通过id查询")
	@ApiOperation(value="巡检主表-通过id查询", notes="巡检主表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Inspection> queryById(@RequestParam(name="id",required=true) String id) {
		Result<Inspection> result = new Result<Inspection>();
		Inspection inspection = inspectionService.getById(id);
		if(inspection==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(inspection);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<Inspection> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              Inspection inspection = JSON.parseObject(deString, Inspection.class);
              queryWrapper = QueryGenerator.initQueryWrapper(inspection, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<Inspection> pageList = inspectionService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "巡检主表列表");
      mv.addObject(NormalExcelConstants.CLASS, Inspection.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("巡检主表列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<Inspection> listInspections = ExcelImportUtil.importExcel(file.getInputStream(), Inspection.class, params);
              inspectionService.saveBatch(listInspections);
              return Result.ok("文件导入成功！数据行数:" + listInspections.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

    @RequestMapping("inspectionTaskList")
	public Result<?>  inspectionTaskList(  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
										   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
										   InspectionTaskRank inspectionTaskRank
										   ) {

  	 Result<Object> result = new Result<>();

		List<String> yearList = com.thinkgem.jeesite.common.utils.DateUtils.getYearList();//年份列表

		List<String> monthList = Lists.newArrayList();//月份列表

		Calendar cale = Calendar.getInstance();
		int year = cale.get(Calendar.YEAR);//当前的年份
		//InspectionTaskRank inspectionTaskRank = new InspectionTaskRank();

		if(null == inspectionTaskRank || 0 == inspectionTaskRank.getYear() || year == inspectionTaskRank.getYear()){//根据当年的年月 往前推11个月 一共12个月

			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");

			String endDate = format.format(new Date());//当前月份

			monthList = com.thinkgem.jeesite.common.utils.DateUtils.getMonthList(12 , endDate);

		}else{
			monthList = com.thinkgem.jeesite.common.utils.DateUtils.getMonthList(12 , inspectionTaskRank.getYear()+"-12");
		}

		String yearCode = null ;

		int yearCount = 0 ;

		List<InspectionTaskRankData> list = Lists.newArrayList();

		InspectionTaskRankData inspectionTaskRankData = new InspectionTaskRankData();

		List<String> months = Lists.newArrayList();

		for(int i = monthList.size() - 1 ; i>=0 ; i-- ){
			String code = monthList.get(i).split("-")[0];
			months.add(com.thinkgem.jeesite.common.utils.DateUtils.getWordMonth( monthList.get(i).split("-")[1]));
			if(StringUtils.isEmpty(yearCode)){
				yearCode = code;
				yearCount++ ;
			}else if(!yearCode.equals(code)){
				inspectionTaskRankData.setYear(yearCode);
				inspectionTaskRankData.setCount(yearCount*2);
				list.add(inspectionTaskRankData);
				inspectionTaskRankData = new InspectionTaskRankData();
				yearCode = code;
				yearCount = 0 ;
				yearCount++ ;
				if(i==0){
					inspectionTaskRankData.setYear(yearCode);
					inspectionTaskRankData.setCount(yearCount*2);
					list.add(inspectionTaskRankData);
				}
			}else{
				yearCount++ ;
				if(i == 0 ){
					inspectionTaskRankData.setYear(yearCode);
					inspectionTaskRankData.setCount(yearCount*2);
					list.add(inspectionTaskRankData);
				}
			}
		}
		//获取主表所有拥有任务的人
		Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
		List<String> officeIds = sysUserRoleService.queryOfficeIds(inspectionTaskRank);
		if(officeIds != null && officeIds.size() > 0){
			inspectionTaskRank.setSqlMap(" and a.office_id in ('"+String.join("','",officeIds)+"') ");
		}else{
			inspectionTaskRank.setSqlMap("and a.office_id = ''");
		}
		List<InspectionTaskRank> inspectionTaskRankList = inspectionService.selectAllPlan(page,inspectionTaskRank);
		if (inspectionTaskRankList.size() <=0 ){
			return null;
		}
		for (InspectionTaskRank ins:inspectionTaskRankList) {
		 List<InspectionTaskRankData> InspectionTaskRankDataList = Lists.newArrayList();
		  //获取人员每月的计划和完成数
			for(int i = monthList.size() - 1 ; i>=0 ; i-- ){
				//每月
				InspectionTaskRankData monthtask = new InspectionTaskRankData();
				//某人当月的计划
				List<Inspection> inspectionList = inspectionService.selectPlanCountData(ins.getUserId(), monthList.get(i));
				if (inspectionList.size()<=0){
					monthtask.setPlanCount(0);
					monthtask.setSuccessCount(0);
					monthtask.setMonths(monthList.get(i));
				}else {
					monthtask.setMonths(monthList.get(i));
					monthtask.setPlanCount(inspectionList.size());
					int a= 0;
					for (Inspection inspection : inspectionList){
						if (inspection.getStatus()== CommonDefine.INSPECTION_STATUS_300){
							a++;
						}
					}
					monthtask.setSuccessCount(a);
				}
				InspectionTaskRankDataList.add(monthtask);
			}
			ins.setInspectionTaskRankDataList(InspectionTaskRankDataList);

		}
		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("inspectionTaskRank",inspectionTaskRankList);
		hashMap.put("months",monthList);
		hashMap.put("yearList",yearList);
		hashMap.put("list",list);
		result.setResult(hashMap);
		return result;
	}
}
